package com.sloth.service.impl;

import com.sloth.mapper.*;
import com.sloth.pojo.*;
import com.sloth.service.OrderDetailService;
import com.sloth.util.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author lai
 * @time 2021/10/7 9:40
 */
@Service
public class OrderDetailServiceImpl implements OrderDetailService {

    @Autowired
    private MyorderMapper myorderMapper;

    @Autowired
    private OrderDetailsMapper orderDetailsMapper;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private FlowMapper flowMapper;

    @Override
    public ServerResponse getByMyOrderIdAndProductId(Integer myOrderId,Integer productId) {

        //传递一个 订单id 用于在订单详情中查询到该订单详情
        OrderDetailsExample orderDetailsExample = new OrderDetailsExample();
        orderDetailsExample.createCriteria().andOrderIdEqualTo(myOrderId).andProIdEqualTo(productId);
        OrderDetails orderDetails = orderDetailsMapper.selectByExample(orderDetailsExample).get(0);


        // 查询该订单选中的收货地址
        Myorder myorder = myorderMapper.selectByPrimaryKey(myOrderId);
        Address address = addressMapper.selectByPrimaryKey(myorder.getAddressId());

        // 查询商品金额
        Product product = productMapper.selectByPrimaryKey(orderDetails.getProId());

        // 查询订单实际付款金额
        FlowExample flowExample = new FlowExample();
        flowExample.createCriteria().andOrderIdEqualTo(myOrderId);
        Flow flow = flowMapper.selectByExample(flowExample).get(0);

        OrderDetailVO orderDetailVO = new OrderDetailVO(orderDetails,address,product,flow,myorder);


        return ServerResponse.getSuccess(orderDetailVO);
    }

    @Override
    public boolean saveOrderDetail(OrderDetails orderDetails) {
        int rows = orderDetailsMapper.insert(orderDetails);

        return rows > 1;
    }

    // 通过 订单id 在订单表中查询属于这个 订单id 的所有订单详情 信息
    @Override
    public List<OrderDetails> getByMyOrderId(Integer myOrderId) {

        OrderDetailsExample orderDetailsExample = new OrderDetailsExample();
        orderDetailsExample.createCriteria().andOrderIdEqualTo(myOrderId);
        List<OrderDetails> orderDetailsList = orderDetailsMapper.selectByExample(orderDetailsExample);

        return orderDetailsList;
    }

    // 修改订单详情中的信息
    @Override
    public Integer updateMyOrderDetail(OrderDetails orderDetails) {
        int rows = orderDetailsMapper.updateByPrimaryKey(orderDetails);
        return rows;
    }
}
